package net.liteheaven.xblib.plugin;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;

public class MPermissionUtil {

    private static final int REQUEST_CODE = 1000;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    public static void grantIOPermissions(Activity activity){
        grantPermissions(activity, PERMISSIONS_STORAGE);
    }

    private static void grantPermissions(Activity activity, String [] permissions){
        for (String permission:permissions) {
            grantPermission(activity, permission);
        }
    }

    private static void grantPermission(Activity activity, String permission){
        if (!isPermissionGranted(activity, permission)) {
            ActivityCompat.requestPermissions(
                    activity,
                    new String[]{permission},
                    REQUEST_CODE
            );
        }
    }

    private static boolean isPermissionGranted(Activity activity, String permission){
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            return ActivityCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED;
        }
        return true;
    }
}
